package com.magupe.push.server.utils;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class MapperUtils {

	public static void processMapper(String id, String address) {
        JSONObject jsonObject = MapperUtils.getMapperJson();
        if(jsonObject == null) {
        	jsonObject = new JSONObject();
        }
        Set<String> keys = jsonObject.keySet();
        Map<String, String> map = new HashMap<String, String>();
        if(keys != null && keys.size() > 0) {
        	for (String key : keys) {
				map.put(key, jsonObject.getString(key));
			}
        }
        map.put(id, address);
        
        writeMapper(JSON.toJSONString(map));
	}
	
	public static String getMapper(String key) {
		JSONObject jsonObject = getMapperJson();
        if(jsonObject == null) {
        	jsonObject = new JSONObject();
        }
		return jsonObject.getString(key);
	}
	
	public static JSONObject getMapperJson() {
		FileInputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		JSONObject jsonObject = null;
		try {
			fis = new FileInputStream(PropertiesUtil.getProperty("server.id-ip.mapper.address"));
			isr = new InputStreamReader(fis, "UTF-8");
			br = new BufferedReader(isr);
			jsonObject = JSONObject.parseObject(br.readLine());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
				isr.close();
				fis.close();
			} catch (IOException e) {e.printStackTrace();}
		}
		
		return jsonObject;
	}
	
	public static void writeMapper(String mapper) {
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
		try {
			fos = new FileOutputStream(PropertiesUtil.getProperty("server.id-ip.mapper.address"));
	        osw = new OutputStreamWriter(fos);
	        osw.write(mapper);
	        osw.write("\r\n");
	        osw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
	        try {
	        	osw.close();
	        	fos.close();
			} catch (IOException e) {e.printStackTrace();}
		}
	}
}
